package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private IAddressBookService addressBookService;

    /**
     * 订单查询
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R order(@RequestBody Orders orders){
        //1.获取操作用户的id
        Long userId = BaseContext.getCurrentId();

        //2.根据id获取购物车数据
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(qw);

        if(shoppingCarts == null || shoppingCarts.size() ==0){
            throw new CustomException("您的购物车空了,不能下单哦");
        }

        //3.获取地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        if(addressBook == null){
            throw new CustomException("请输入地址才能下单哦");
        }

        //4.获取用户信息
        User user = userService.getById(userId);

        AtomicInteger amount = new AtomicInteger(0);

        long orderId = IdWorker.getId();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            //把shoppingCart中的数据拷贝到orderDetail中
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orderId);
            amount.addAndGet(shoppingCart.getAmount().multiply((new BigDecimal(shoppingCart.getNumber()))).intValue());
            orderDetailService.save(orderDetail);
        }

        //5.获取订单表数据
        orders.setAmount(new BigDecimal(amount.get()));

        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setStatus(2);//待支付订单
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(1);//微信
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setAddress(addressBook.getDetail() == null ? "" : addressBook.getDetail());

        //向订单表插入数据
        orderService.save(orders);
        //向订单明细表插入数据
        //清空购物车数据
        shoppingCartService.remove(qw);

        return R.success("订单查询成功");
    }

    /**
     * 手机端分页查询订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R page(Integer page,Integer pageSize){
        Long id = BaseContext.getCurrentId();
        Page<Orders> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,id);
        orderService.page(pageInfo,qw);

        Integer total = Math.toIntExact(pageInfo.getTotal());
        List<Orders> records = pageInfo.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("records",records);
        return R.success(map);
    }

    /**
     * 后台订单明细表
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R page1(Integer page,Integer pageSize){
        Long id = BaseContext.getCurrentId();
        Page<Orders> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,id);
        orderService.page(pageInfo,qw);

        Integer total = Math.toIntExact(pageInfo.getTotal());
        List<Orders> records = pageInfo.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("records",records);

        OrdersDto ordersDto = new OrdersDto();
        return R.success(map);
    }
}
